package org.service.Impl;

import org.Tian.JdbcUtil;
import org.pojo.User;
import org.service.UserDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    //对数据库表进行查询
    @Override
    public List<User> queryAll() {
        //实现的是查询功能，查询一张表
        List<User> userList=new ArrayList<>();
        //查询一张表，这里可以直接写到下面的括号里，查询语句，我们要查什么就写什么
        String sql = "select id,name,sex,address,phone from user";
        //我们自己来装表
        try(Connection connection = JdbcUtil.getConnection();
            //写sql语句对数据库进行操作
            PreparedStatement ps = connection.prepareStatement(sql);
            ResultSet resultSet = ps.executeQuery()){
            while (resultSet.next()){
                User user = new User();
                //这里的五个字段就是上面对应的sql字段
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"));
                user.setSex(resultSet.getInt("sex"));
                user.setAddress(resultSet.getString("address"));
                user.setPhone(resultSet.getString("phone"));
                userList.add(user);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return userList;
    }
    @Override
    public int insert(User user) {
        int result = 0;
        String sql = "insert into user(name,sex,address,phone) values(?,?,?,?)";
        //进行数据库的连接
        try(Connection connection = JdbcUtil.getConnection();
        PreparedStatement ps = connection.prepareStatement(sql)){
            ps.setString(1,user.getName());
            ps.setInt(2,user.getSex());
            ps.setString(3,user.getAddress());
            ps.setString(4,user.getPhone());
            result = ps.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }
        //这里是要返回的值
        return result;
    }

    @Override
    public int delete(User user) {
        return 0;
    }

    @Override
    public int update(User user) {
        return 0;
    }
}
